<template>
  <div>
    <el-card>
      <el-row style="margin-bottom: 5px">
        <el-col :span="6">
          <el-input style="width:440px" @clear="searchUser" clearable v-model="searchForm.name" placeholder="请输入书籍名称"
                    class="input-with-select">
            <template #append>
              <el-button icon="Search" @click="searchUser"/>
            </template>
          </el-input>
        </el-col>
        <el-col :span="2" style="margin-left: 25px">
          <el-button size="primary"
                     @click="() => router.push({ path: '/book/save'})">新增书籍
          </el-button>
        </el-col>
        <el-col :span="1">
          <el-upload
              class="upload-demo"
              action="http://localhost:3000/api/book/importBook"
              :show-file-list="false"
              :on-success="handleSuccess"
              :on-error="handleError"
              accept=".csv,.xlsx"
          >
            <el-button size="primary" type="primary">点击上传</el-button>
          </el-upload>
        </el-col>
        <el-col :span="2">
          <el-button size="primary" type="primary" @click= "exportBook">点击导出</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="bookid" label="序列号" width="180"/>
        <el-table-column prop="bookname" label="书名" width="180"/>
        <el-table-column prop="bookcounts" label="数量" width="180"/>
        <el-table-column prop="detail" label="描述" width="180"/>
        <el-table-column prop="type" label="类型" width="180"/>
        <el-table-column prop="date" label="创建日期" width="180"/>
        <el-table-column prop="操作" label="操作">
          <template #default="scope">
            <el-button type="danger" size="small" @click="deleteUser(scope.row.bookid)">删除</el-button>
            <el-button size="small"
                       @click="() => router.push({ path: '/book/detail', query: { id: scope.row.bookid } })">详情
            </el-button>
            <el-button type="primary" size="small" @click="() => router.push({ path: '/book/update', query: { id: scope.row.bookid } })">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination style="margin-top:20px" :current-page="searchForm.current" :page-size="searchForm.size"
                     :page-sizes="[10, 20, 30, 40]" layout="->,total, sizes, prev, pager, next, jumper" :total="total"
                     @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
    </el-card>
  </div>
</template>

<script setup>
import userApi from "../../api/user";
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from 'element-plus';
import {useRouter} from 'vue-router'
import instance from "../../utils/http/axios";

const router = useRouter();
// Dom 挂载之后
onMounted(() => {
  getUserList();
})
// 用户数据
let tableData = ref([]);
let total = ref(0);
// 搜索条件
const searchForm = reactive({
  current: 1,
  size: 10,
  name: '',
  file:''
})
// 获取用户列表
const getUserList = async () => {
  const res = await userApi.getUserList(searchForm);
  console.log(res);
  tableData.value = res.data.data;
  total.value = res.data.count;
}
const handleSizeChange = (size) => {
  searchForm.size = size;
  getUserList();
}
const handleCurrentChange = (current) => {
  searchForm.current = current;
  getUserList();
}
const searchUser = () => {
  searchForm.current = 1;
  getUserList();
}
// 删除用户
const deleteUser = (id) => {
  ElMessageBox.confirm(
      '确定要删除该用户信息吗?',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    const res = await userApi.delUser({id: id});
    if (res.data.success) {
      ElMessage.success("删除成功")
      getUserList();
    } else {
      ElMessage.error("删除失败")
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}

/*const handleFileUpload = async (file) => {
  if (file.length === 0) return;
  searchForm.file=file.raw;
  const res = await userApi.importFile(searchForm);
  if (res.data.success) {
    ElMessage.success("导入成功")
    searchForm.file='';
  } else {
    ElMessage.error("导入失败")
    searchForm.file='';
  }
}*/
const exportBook = async (searchForm)=>{
  await instance
      .post("http://localhost:3000/api/book/exportBook", searchForm,{responseType: 'blob'})
      .then((resp) => {
        console.log("resp:",resp.data)
        const blob = new Blob([resp.data]);
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob);
        downloadElement.href = href;
        downloadElement.download = 'data.xlsx';
        downloadElement.click();
        window.URL.revokeObjectURL(href);
      })
}

const handleSuccess = (response, file, fileList) => {
  ElMessage.success("导入成功")
  getUserList();
}
const handleError = (err, file, fileList) => {
  ElMessage.success("导入失败")
}


</script>

<style lang="scss" scoped>
</style>